﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WindowsFormsApp1.Exception;

namespace WindowsFormsApp1.utils
{
    public class DataBackupUtil
    {

        private readonly string delTable_2017 = "drop table if exists #T;";
        private readonly string delTable_2005 = @"If Object_Id('Tempdb.dbo.#T') Is Not Null
                                                  drop table #T;";



        private readonly string databaseVersion = "select @@VERSION;";


        private string createAndInsrtLsTable = @"
                                    create table #T
                                    (
                                    databasename varchar(30),
                                    logsize float,
                                    logspaceuserd float,
                                    status bit
                                    );
            insert into #T execute('dbcc sqlperf(logspace) with no_infomsgs');";

        private string crea_prdu = @"CREATE PROCEDURE GetStuCou
                                    as
                                    begin
                                    declare @pages int  
                                    declare @dbname sysname  
                                    declare @dbsize dec(15,0)  
                                    declare @logsize dec(15)  
                                    declare @bytesperpage dec(15,0)  
                                    declare @pagesperMB  dec(15,0)  
                                     select @dbsize = sum(convert(dec(15),size))  
                                      from dbo.sysfiles  
                                      where (status & 64 = 0)  
                                     select @logsize = sum(convert(dec(15),size))  
                                      from dbo.sysfiles  
                                      where (status & 64 <> 0)  
                                     select @bytesperpage = low  
                                      from master.dbo.spt_values  
                                      where number = 1  
                                       and type = 'E'  
                                     select @pagesperMB = 1048576 / @bytesperpage  
                                     select  database_name = db_name(),  
                                      database_size =  
                                       ltrim(str((@dbsize + @logsize) / @pagesperMB,15,2) + ' MB'),  
                                      'unallocated space' =  
                                       ltrim(str((@dbsize -  
                                        (select sum(convert(dec(15),reserved))  
                                         from sysindexes  
                                          where indid in (0, 1, 255)  
                                        )) / @pagesperMB,15,2)+ ' MB')  
                                    end";


        private string del_prdu_2017 = "DROP PROCEDURE if exists GetStuCou";
        private string del_prdu_2005 = @"
                                        if OBJECT_ID('GetStuCou') IS NOT NULL
                                        drop PROCEDURE GetStuCou";

        private string createInsertLsTable_dataSize = @"
                                    create table #T
                                    (
                                    databasename varchar(30),
                                    database_size varchar(30),
                                    unallocated_space varchar(30)
                                    );
            insert into #T execute('exec GetStuCou');";



        private string create_for_find_free_size = @"IF OBJECT_ID('Tempdb.dbo.#TempDrive') IS NOT NULL DROP TABLE #TempDrive;
                                                    CREATE TABLE #TempDrive 
                                                    (           
                                                        [DriveName] NVARCHAR(10),
                                                        [DriveFreeSpace] BIGINT    
                                                    ) 
                                                     INSERT INTO #TempDrive 
                                                     EXECUTE [master].[dbo].xp_fixeddrives
                                                     SELECT * FROM #TempDrive;";
        private string deltable_server = "IF OBJECT_ID('Tempdb.dbo.#TempDrive') IS NOT NULL DROP TABLE #TempDrive;";


        public void DataBack(SqlConnection conn , string DBName ,string sqlIp = "" , string username = "", string password = "", string fileName = "")
        {
            System.Diagnostics.Debug.WriteLine($"===================开始进行数据库:{DBName}数据备份====================");
            string path = "D://管理系统数据库手动备份//DBBakcup//DB//" + DBName;


            string netbackfile = "\\\\" + sqlIp + "\\Users\\Public\\lsdl\\DB\\" + DBName;


            //判断磁盘空间大小
            if (GetHardDiskFreeSpace("D") < 52428800)
            {
                System.Diagnostics.Debug.WriteLine("===================数据备份失败====================");
                throw new System.Exception("磁盘空间不足");
            }

            //判断文件夹路径是否存在
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            
            string databasefile = fileName == "" ? path + "//" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".bak" : path + "//" + fileName;
            string sql = fileName == "" ? "BACKUP DATABASE " + DBName + " TO DISK = '" + databasefile + "'" : "BACKUP DATABASE " + DBName + " TO DISK = '" + databasefile + "' with DIFFERENTIAL;";
            using (SqlCommand cmd = new SqlCommand())
            {
                //设置DBCommand的超时事件
                cmd.CommandTimeout = 1000000000;
                try
                {
                    cmd.Connection = conn;
                    if(sqlIp != "")
                    {
                        //创建共享文件夹
                        if (!Directory.Exists(netbackfile))
                        {
                            Directory.CreateDirectory(netbackfile);
                        }
                        netDataBack(conn, netbackfile, DBName, username, password, fileName);
                        MoveFile(netbackfile, path);
                    }
                    else
                    {
                        cmd.CommandText = sql;
                        cmd.ExecuteNonQuery();
                    }
                }
                catch (System.Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"===================数据备份失败,原因为{ex.Message}====================");
                    throw new System.Exception(ex.Message);
                }
            }
            
            System.Diagnostics.Debug.WriteLine($"===================数据库{DBName}数据备份成功====================");
        }


        //远程创建服务器上文件夹，并进行数据库备份
        public void netBackupData_createFileForServer(SqlConnection conn, string DBName, string fileName = "")
        {
            System.Diagnostics.Debug.WriteLine($"===================开始进行数据库:{DBName}数据备份====================");
            string backup_path = $"E:\\数据库备份文件储存\\DB\\{DBName}";
            string create_path = $"exec xp_create_subdir N'{backup_path}';";
            string sql = fileName == "" ? $"BACKUP DATABASE {DBName} TO DISK = '{backup_path}\\{DateTime.Now.ToString("yyyyMMddHHmmss")}.bak'":
                    $"BACKUP DATABASE {DBName} TO DISK = '{backup_path}\\{fileName}' with DIFFERENTIAL;";
            string disk_zie = null;
            try
            {
                using (SqlCommand cmd = new SqlCommand(create_for_find_free_size, conn))
                {
                    //判断文件夹大小
                    var reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        if (reader[0].ToString() == "E")
                        {
                            disk_zie = reader[1].ToString();
                            break;
                        }
                    }
                    reader.Close();
                    //删除临时表
                    cmd.CommandText = deltable_server;
                    cmd.ExecuteNonQuery();
                    if (int.Parse(disk_zie) < getDataBaseFileSize(cmd, DBName))
                    {
                        System.Diagnostics.Debug.WriteLine("===================数据备份失败====================");
                        throw new System.Exception("磁盘E 空间不足无法进行备份");
                    }
                    //创建文件夹
                    cmd.CommandText = create_path;
                    cmd.ExecuteNonQuery();
                    //数据库备份
                    cmd.CommandText = sql;
                    cmd.ExecuteNonQuery();
                }
            }
            catch (System.Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"===================数据备份失败,原因为{ex.Message}====================");
                throw new System.Exception(ex.Message);
            }
            System.Diagnostics.Debug.WriteLine($"===================数据库{DBName}数据备份成功====================");
        }




        //远程创建服务器上文件夹，并进行数据库日志备份
        public void netBackupLog_createFileForServer(SqlConnection conn, string DBName, float logSize)
        {
            System.Diagnostics.Debug.WriteLine($"===================数据库{DBName}开始进行日志备份====================");
            float logSizeWithoutClean = 0f;
            string disk_zie = null;
            string dateName = DateTime.Now.ToString("yyyyMMddHHmmss");
            SqlDataReader reader = null;
            string changeMode = $@"ALTER DATABASE {DBName} SET RECOVERY FULL WITH NO_WAIT 
                                   ALTER DATABASE {DBName} SET RECOVERY FULL";
            string backup_path = $"E:\\数据库备份文件储存\\Log\\{DBName}";
            string create_path = $"exec xp_create_subdir N'{backup_path}';";

            string logBackup = $"BACKUP LOG {DBName} TO DISK = '{backup_path}\\{dateName}.bak'";
            string delBackUp = $@"USE master
                                ALTER DATABASE {DBName} SET RECOVERY SIMPLE WITH NO_WAIT
                                ALTER DATABASE {DBName} SET RECOVERY SIMPLE
                                USE {DBName} 
                                DBCC SHRINKFILE (N'{DBName}_log' , 2 , TRUNCATEONLY)
                                USE master
                                ALTER DATABASE {DBName} SET RECOVERY FULL WITH NO_WAIT 
                                ALTER DATABASE {DBName} SET RECOVERY FULL";
            try
            {
                using (SqlCommand cmd = new SqlCommand(create_for_find_free_size, conn))
                {
                    //判断文件夹大小
                    reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        if (reader[0].ToString() == "E")
                        {
                            disk_zie = reader[1].ToString();
                            break;
                        }
                    }
                    reader.Close();
                    //删除临时表
                    cmd.CommandText = deltable_server;
                    cmd.ExecuteNonQuery();
                    if (int.Parse(disk_zie) < getDataBaseFileSize(cmd, DBName))
                    {
                        System.Diagnostics.Debug.WriteLine("===================数据备份失败====================");
                        throw new System.Exception("磁盘E 空间不足无法进行备份");
                    }
                    //创建文件夹
                    cmd.CommandText = create_path;
                    cmd.ExecuteNonQuery();
                    //查询清理前日志文件大小
                    logSizeWithoutClean = findLogSize(cmd, DBName);
                    //判断日志大小是否超过阈值
                    if (logSizeWithoutClean > logSize)
                    {
                        //完全备份
                        netBackupData_createFileForServer(conn, DBName, dateName + "前置差异备份.bak");

                        //判断并且更改数据库的备份模式
                        reader = cmd.ExecuteReader();
                        while (reader.Read())
                        {
                            if (reader[0].ToString() != ("FULL"))
                            {
                                reader.Close();
                                cmd.CommandText = changeMode;
                                cmd.ExecuteNonQuery();
                                break;
                            }
                        }
                        reader.Close();

                        //日志备份
                        cmd.CommandText = logBackup;
                        cmd.ExecuteNonQuery();
                        //删除日志
                        cleanDB(cmd, DBName, logSizeWithoutClean);
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine($"===================日志大小未达到阈值{logSize}，无需备份====================");
                        throw new System.Exception($"日志大小未达到阈值{logSize} \n 当前日志大小为{logSizeWithoutClean}MB，无需备份");
                    }
                }
            }
            catch (MyException myex)
            {
                System.Diagnostics.Debug.WriteLine($"===================日志备份成功，日志文清理结果为{myex.Message}:====================");
                throw new MyException(myex.Message);
            }
            catch (System.Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"===================日志备份失败，原因为{ex.Message}:====================");
                throw new System.Exception(ex.Message);
            }
            System.Diagnostics.Debug.WriteLine($"===================数据库{DBName}日志备份结束====================");

        }




        public void LogBack(SqlConnection conn, string DBName, float logSize, string sqlIp = "", string username = "", string password = "")
        {
            float logSizeWithoutClean = 0f;
            string databaseBackupState = $"SELECT recovery_model_desc FROM sys.databases WHERE name = '{DBName}'";
            string selectFromLsTable = "select logsize from #T where databasename = '" + DBName + "'";
            string changeMode = $@"ALTER DATABASE {DBName} SET RECOVERY FULL WITH NO_WAIT 
                                   ALTER DATABASE {DBName} SET RECOVERY FULL";

            string path = "BACKUP log " + DBName + " TO DISK = '";
            string dicPath = "D://管理系统数据库手动备份//DBBakcup//Log//" + DBName;
            string dateName = DateTime.Now.ToString("yyyyMMddHHmmss");
            string logBackup = path + dicPath + "//" + dateName + ".bak'";

            string delBackUp = $@"USE master
                                ALTER DATABASE {DBName} SET RECOVERY SIMPLE WITH NO_WAIT
                                ALTER DATABASE {DBName} SET RECOVERY SIMPLE
                                USE {DBName} 
                                DBCC SHRINKFILE (N'{DBName}_log' , 2 , TRUNCATEONLY)
                                USE master
                                ALTER DATABASE {DBName} SET RECOVERY FULL WITH NO_WAIT 
                                ALTER DATABASE {DBName} SET RECOVERY FULL";

            string netBackfile = "\\\\" + sqlIp + "\\Users\\Public\\lsdl\\Log\\" + DBName;




            if (GetHardDiskFreeSpace("D") < 52428800)
            {
                System.Diagnostics.Debug.WriteLine("===================数据备份失败====================");
                throw new System.Exception("磁盘空间不足");
            }

            //判断文件夹路径是否存在
            if (!Directory.Exists(dicPath))
            {
                Directory.CreateDirectory(dicPath);
            }


            System.Diagnostics.Debug.WriteLine($"===================数据库{DBName}开始进行日志备份====================");
            try
            {
                using (SqlCommand cmd = new SqlCommand(databaseBackupState, conn))
                {
                    //设置DBCommand的超时事件
                    cmd.CommandTimeout = 1000000000;
                    //判断并且更改数据库的备份模式
                    SqlDataReader reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        if (reader[0].ToString() != ("FULL"))
                        {
                            reader.Close();
                            cmd.CommandText = changeMode;
                            cmd.ExecuteNonQuery();
                            break;
                        }
                    }
                    reader.Close();

                    //查询清理前日志文件大小
                    logSizeWithoutClean = findLogSize(cmd, DBName);
                    //判断日志大小是否超过阈值
                    if (logSizeWithoutClean > logSize)
                    {
                        if (sqlIp != "")
                        {
                            //创建共享文件夹
                            if (!Directory.Exists(netBackfile))
                            {
                                Directory.CreateDirectory(netBackfile);
                            }

                            //差异备份
                            DataBack(conn, DBName, sqlIp, username, password, dateName + "前置差异备份.bak");
                            netLogBack(conn, netBackfile, DBName, username, password, dateName);
                            MoveFile(netBackfile, dicPath);
                        }
                        else
                        {
                            //差异备份
                            DataBack(conn, DBName,"","","", dateName + "前置差异备份.bak");
                            //日志备份
                            cmd.CommandText = logBackup;
                            cmd.ExecuteNonQuery();
                        }
                        //删除日志
                        cleanDB(cmd, DBName, logSizeWithoutClean);
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine($"===================日志大小未达到阈值{logSize}，无需备份====================");
                        throw new System.Exception($"日志大小未达到阈值{logSize} \n 当前日志大小为{logSizeWithoutClean}MB，无需备份");
                    }
                }
            }
            catch (MyException myex)
            {
                System.Diagnostics.Debug.WriteLine($"===================日志备份成功，日志文清理结果为{myex.Message}:====================");
                throw new MyException(myex.Message);
            }
            catch (System.Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"===================日志备份失败，原因为{ex.Message}:====================");
                throw new System.Exception(ex.Message);
            }
            System.Diagnostics.Debug.WriteLine($"===================数据库{DBName}日志备份结束====================");
        }



        public void netDataBack(SqlConnection conn, string path, string DBName, string username, string password, string fileName = "")
        {
            string dateName = DateTime.Now.ToString("yyyyMMddHHmmss");
            string open_xp = "EXEC sp_configure 'show advanced options', 1;RECONFIGURE;EXEC sp_configure 'xp_cmdshell', 1;RECONFIGURE;";
            string create_link = "exec master..xp_cmdshell 'net use z:  " + path + "  " + password + " /user:" + username + "';";
            string copy_to_sharefile = fileName == "" ? "backup database " + DBName + " to disk='z:\\\\" + dateName + ".bak' with noformat ,MAXTRANSFERSIZE = 4194304 ,BUFFERCOUNT=100;"
                : "backup database " + DBName + " to disk='z:\\\\" +  fileName + "' with DIFFERENTIAL,noformat ,MAXTRANSFERSIZE = 4194304 ,BUFFERCOUNT=100;";
            string del_link = "exec master..xp_cmdshell 'net use z: /delete';";
            string close_xp = @"EXEC sp_configure 'xp_cmdshell', 0;RECONFIGURE;
                                EXEC sp_configure 'show advanced options', 0; RECONFIGURE; ";
            using (SqlCommand cmd = new SqlCommand())
            {
                //设置超时时间
                cmd.CommandTimeout = 1000000000;
                cmd.Connection = conn;
                //开启xp
                cmd.CommandText = open_xp;
                cmd.ExecuteNonQuery();
                //创建连接
                cmd.CommandText = create_link;
                cmd.ExecuteNonQuery();
                //备份进共享文件夹
                cmd.CommandText = copy_to_sharefile;
                cmd.ExecuteNonQuery();
                //删除连接
                cmd.CommandText = del_link;
                cmd.ExecuteNonQuery();
                //关闭xp
                cmd.CommandText = close_xp;
                cmd.ExecuteNonQuery();

            }
        }

        public void netLogBack(SqlConnection conn, string path, string DBName, string username, string password ,string dateName)
        {
            string open_xp = "EXEC sp_configure 'show advanced options', 1;RECONFIGURE;EXEC sp_configure 'xp_cmdshell', 1;RECONFIGURE;";
            string create_link = "exec master..xp_cmdshell 'net use z:  " + path + "  " + password + " /user:" + username + "';";
            string copy_to_sharefile = "backup log " + DBName + " to disk='z:\\\\" + dateName + ".bak'with noformat ,MAXTRANSFERSIZE = 4194304 ,BUFFERCOUNT=100;";
            string del_link = "exec master..xp_cmdshell 'net use z: /delete';";
            string close_xp = @"EXEC sp_configure 'xp_cmdshell', 0;RECONFIGURE;
                                EXEC sp_configure 'show advanced options', 0; RECONFIGURE; ";
            using (SqlCommand cmd = new SqlCommand())
            {
                //设置超时时间
                cmd.CommandTimeout = 1000000000;
                cmd.Connection = conn;
                //开启xp
                cmd.CommandText = open_xp;
                cmd.ExecuteNonQuery();
                //创建连接
                cmd.CommandText = create_link;
                cmd.ExecuteNonQuery();
                //备份进共享文件夹
                cmd.CommandText = copy_to_sharefile;
                cmd.ExecuteNonQuery();
                //删除连接
                cmd.CommandText = del_link;
                cmd.ExecuteNonQuery();
                //关闭xp
                cmd.CommandText = close_xp;
                cmd.ExecuteNonQuery();

            }
        }



        public static long GetHardDiskFreeSpace(string str_HardDiskName)
        {
            long freeSpace = new long();
            str_HardDiskName = str_HardDiskName + ":\\";
            DriveInfo[] drives = DriveInfo.GetDrives();
            foreach (DriveInfo drive in drives)
            {
                if (drive.Name == str_HardDiskName)
                {
                    freeSpace = drive.TotalFreeSpace;
                }
            }
            return freeSpace;
        }



        public void cleanDB(SqlCommand cmd, string DBName, float logSizeWithoutClean = 0f)
        {
            float logSizeCleaned = 0f;
            string delBackUp = $@"USE master
                                ALTER DATABASE {DBName} SET RECOVERY SIMPLE WITH NO_WAIT
                                ALTER DATABASE {DBName} SET RECOVERY SIMPLE
                                USE {DBName} 
                                DBCC SHRINKFILE (N'{DBName}_log' , 2 , TRUNCATEONLY)
                                USE master
                                ALTER DATABASE {DBName} SET RECOVERY FULL WITH NO_WAIT 
                                ALTER DATABASE {DBName} SET RECOVERY FULL";
            string selectFromLsTable = "select logsize from #T where databasename = '" + DBName + "'";
            try
            {
                if (logSizeWithoutClean == 0)
                {
                    //查询清理前日志文件大小
                    logSizeWithoutClean = findLogSize(cmd, DBName);

                }
                //收缩日志文件
                cmd.CommandText = delBackUp;
                cmd.ExecuteNonQuery();
                //查询清理日志后文件大小
                logSizeCleaned = findLogSize(cmd, DBName);
                throw new MyException($"数据库{DBName}清理成功 \n 清理前数据库日志大小为:{logSizeWithoutClean} \n 清理后数据库日志大小为:{logSizeCleaned}");
            }
            catch (MyException myex)
            {
                throw new MyException(myex.Message);
            }
            catch(System.Exception ex)
            {
                throw new System.Exception(ex.Message);
            }

        }


        public float findLogSize(SqlCommand cmd, string DBName)
        {
            string delLsTable = null;
            string createAndInsrtLsTableAsync = null;
            string selectFromLsTable = "select logsize from #T where databasename = '" + DBName + "'";
            float logSize = 0f;
            //判断数据库版本
            if (Int64.Parse(getDataBaseVersion(cmd)) < 2017)
            {
                createAndInsrtLsTableAsync = delTable_2005 + createAndInsrtLsTable;
                delLsTable = delTable_2005;
            }
            else
            {
                createAndInsrtLsTableAsync = delTable_2017 + createAndInsrtLsTable;
                delLsTable = delTable_2017;
            }
            try
            {
                //创建临时表
                cmd.CommandText = createAndInsrtLsTableAsync;
                cmd.ExecuteNonQuery();
                //查询
                cmd.CommandText = selectFromLsTable;
                var reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    logSize = float.Parse(reader[0].ToString());
                    break;
                }
                reader.Close();
                //删除临时表
                cmd.CommandText = delLsTable;
                cmd.ExecuteNonQuery();
                //返回日志大小
                return logSize;
            }catch(System.Exception ex)
            {
                throw new System.Exception(ex.Message);
            }
        }


        //获取sql server的版本
        public string getDataBaseVersion(SqlCommand cmd)
        {
            try
            {
                cmd.CommandText = databaseVersion;
                var reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    string version = reader[0].ToString().Split(' ').GetValue(3).ToString().Trim();
                    reader.Close();
                    return version;
                }
                return "";
            }catch(System.Exception ex)
            {
                throw new System.Exception(ex.Message);
            }
        }



        public float getDataBaseFileSize(SqlCommand cmd, string DBName)
        {
            string delLsTable = null;
            string createAndInsrtLsTableAsync = null;
            string del_prdu = null;
            try
            {
                //判断数据库版本
                if (Int64.Parse(getDataBaseVersion(cmd)) < 2017)
                {
                    createAndInsrtLsTableAsync = delTable_2005 + createInsertLsTable_dataSize;
                    delLsTable = delTable_2005;
                    del_prdu = del_prdu_2005;
                }
                else
                {
                    createAndInsrtLsTableAsync = delTable_2017 + createInsertLsTable_dataSize;
                    delLsTable = delTable_2017;
                    del_prdu = del_prdu_2017;
                }
                string size = null;
                cmd.CommandText = $"use {DBName}";
                cmd.ExecuteNonQuery();
                //删除存储过程
                cmd.CommandText = del_prdu;
                cmd.ExecuteNonQuery();

                cmd.CommandText = crea_prdu;
                cmd.ExecuteNonQuery();
                //创建零时表
                cmd.CommandText = createAndInsrtLsTableAsync;
                cmd.ExecuteNonQuery();
                //删除存储过程
                cmd.CommandText = del_prdu;
                cmd.ExecuteNonQuery();
                //查询
                cmd.CommandText = "select * from #T";
                var reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    size = reader[1].ToString();
                    break;
                }
                reader.Close();
                //删除零时表
                cmd.CommandText = delLsTable;
                cmd.ExecuteNonQuery();
                return float.Parse(size.Split(' ')[0]);
                
            }
            catch (System.Exception ex)
            {
                throw new System.Exception(ex.Message);
            }
        }

        //移动文件
        private void MoveFile(string Frompath, string directoryPath)
        {
            try
            {
                string[] bakList = Directory.GetFiles(Frompath, "*.bak");

                
                foreach (string f in bakList)
                {
                    string fName = f.Substring(Frompath.Length + 1);
                    try
                    {
                        File.Copy(Path.Combine(Frompath, fName), Path.Combine(directoryPath, fName));
                    }
                    // 捕捉异常.
                    catch (IOException copyError)
                    {
                        MessageBox.Show(copyError.Message);
                    }
                }
                foreach (string f in bakList)
                {
                    File.Delete(f);
                }
            }
            catch (DirectoryNotFoundException dirNotFound)
            {
                MessageBox.Show(dirNotFound.Message);
            }
        }


    }

}
